import JsonP from 'jsonp';
import axios from 'axios';
// 引用qs模块处理axios发送的数据
import qs from 'qs';

const root = 'https://www.easy-mock.com/mock/5b67d61a8ea81964e5f5deca/mock_api';

// 自定义判断元素类型JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key];
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim();
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key]);
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key]);
    }
  }
  return o;
}

export default class Api {

  static jsonp(url) {
    //json请求
    return new Promise((resolve, reject) => {
      JsonP(url, {
        param: 'callback'
      }, function (err, res) {
        // to-do
        if (res.status == "success") {
          resolve(res);
        } else {
          reject(res.message);
        }
      })
    })
  }

  static ajax(method,url,params,options) {
    return new Promise((resolve, reject) => {
      if (params) {
        params = filterNull(params);
      }
      axios({
        method: method,
        url: url,
        baseURL: root,
        timeout: 5000,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
        data: method === 'POST' || method === 'post' ? qs.stringify(params) : null,
        params: method === 'GET' || method === 'get' ? params : null,
        withCredentials: true
      }).then((res) => {
        if (res.status === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      }).catch((err) => {
        //请求失败
        console.log(err);
      })
    })
  }
}
